package com.ajun.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.ajun.util.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

//设置跨域
@CrossOrigin
@RestController
@RequestMapping("/files")
public class FileController {

    @Value("${server.port}")
    private String port;

    private static final String ip = "http://localhost";

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String flag = IdUtil.fastSimpleUUID();
        String originalFilename = file.getOriginalFilename();
        String fileName = flag + "_" + originalFilename;
        String rootFilePath = System.getProperty("user.dir") + "/ajun-Content/src/main/resources/files/" + fileName;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        return R.ok().data("pic",ip + ":" + port + "/files/" + fileName);
    }


    @PostMapping("/editor/upload")
    public JSON editorUpload(MultipartFile file) throws IOException {
        String flag = IdUtil.fastSimpleUUID();
        String originalFilename = file.getOriginalFilename();
        String fileName = flag + "_" + originalFilename;
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + fileName;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        String url=ip+":"+port+"/files/"+fileName;
        JSONObject json=new JSONObject();
        json.set("errno",0);
        JSONArray arr=new JSONArray();
        JSONObject data=new JSONObject();
        arr.add(data);
        data.set("url",url);
        json.set("data",arr);
        return json;
    }

    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;
        String basePath = System.getProperty("user.dir") + "/ajun-Content/src/main/resources/files/";
        try {

            if (StrUtil.isNotEmpty(flag)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, String.valueOf(StandardCharsets.UTF_8)));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + flag);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }
}
